import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 5000 // request timeout
})
// 请求拦截器
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // 把token放在请求拦截器的请求头上，不用每次都添加了
      config.headers['Authorization'] = `Bearer ${store.getters.token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
// 响应拦截器
// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // console.log('请求拦截', response)中间要加逗号，要不输出的是对象数组
    // console.log('请求拦截', response)
    // data就是后台返回的token
    const { data, message, success } = response.data
    if (success) {
      return data
    } else {
      Message({
        message: message,
        type: 'error',
        duration: 3 * 1000
      })
      // 需要抛出一个promice的错误，这样外面组件也可以捕获这个错误
      return Promise.reject(new Error(message))
    }
  },
  error => {
    // console.log('err' + error) // for debug
    console.dir(error)
    if (error.response.status === 401) {
      // 处理某些页面多个请求多次401重复跳转问题，造成重新登录后不能正确跳转到上次访问页面问题
      if (router.currentRoute.path === '/login') return
      // token失效的信息提示
      Message({
        message: error.response.data.message,
        type: 'error',
        duration: 3 * 1000
      })
      // 清空token,以及用户信息
      store.dispatch('user/logOutActions')
      // 跳转登录页面的操作
      // router.currentRoute.path当前登录页面的路由地址
      router.replace(`/login?redirect=${router.currentRoute.path}`)
    }
    return Promise.reject(error)
  }
)

export default service
